package com.woniuxy.ticketauth.config;

import com.woniuxy.ticketauth.shiro.*;
import org.apache.shiro.authc.pam.FirstSuccessfulStrategy;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName ShiroConfig
 * @Description TODO
 * @Author zx
 * @Date 2021-03-03 14:13:37
 * @Version 1.0
 */
@Configuration
public class ShiroConfig {
    @Bean
    public DbRealm dbRealm(){
        return new DbRealm();
    }

    @Bean
    public Realm jwtRealm() {
        return new JwtRealm();
    }

    //安全管理器
    @Bean
    public DefaultWebSecurityManager securityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//        securityManager.setRealm(dbRealm());
        //多个realm
//        securityManager.setRealms(Arrays.asList(dbRealm(),jwtRealm()));
        MultiRealmAuthenticator authenticator = new MultiRealmAuthenticator();
        authenticator.setRealms(Arrays.asList(dbRealm(),jwtRealm()));
        authenticator.setAuthenticationStrategy(new FirstSuccessfulStrategy());
        securityManager.setAuthenticator(authenticator);
        //设置授权器为DbRealm
        securityManager.setAuthorizer(dbRealm());
        return securityManager;
    }

    @Bean
    public JwtFilter jwtFilter(){
        return new JwtFilter();
    }

    public MyPermissionsAuthorizationFilter myPermissionsAuthorizationFilter(){
        return new MyPermissionsAuthorizationFilter();
    }

    /**
     * 核心Bean
     * 主要来指定哪些请求需要认证、哪些不需要、哪些需要什么样的权限
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager());
        //增加自定的过滤器
        Map<String, Filter> filterMap =new HashMap<>();
        filterMap.put("jwt",jwtFilter());
        filterMap.put("perms",myPermissionsAuthorizationFilter());
        shiroFilterFactoryBean.setFilters(filterMap);
        //配置请求的URl与过滤器的关系
//        Map<String, String> map = new LinkedHashMap<>();
//        map.put("/manager/login","anon");
//        map.put("/menu/get","jwt");
//        map.put("/movie/add","jwt,perms[movie:add]");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(permMapFactoryBean().getObject());
        return shiroFilterFactoryBean;
    }

    @Bean
    public PermMapFactoryBean permMapFactoryBean() {
        return new PermMapFactoryBean();
    }
}
